<template>
    <PageLayout>
        <div style="width: 100%">
            <div class="search-h">
                <div style="flex: 1">
                    <a-form
                        layout="horizontal"
                        :form="queryParams"
                    >
                        <a-row>
                            <a-col
                                :md="12"
                                :sm="24"
                            >
                                <a-form-item
                                    label="名称"
                                    :label-col="{ span: 5 }"
                                    :wrapper-col="{ span: 18, offset: 1 }"
                                >
                                    <a-input
                                        v-model="queryParams.name"
                                        placeholder="输入名称"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <div>
                    <a-button
                        type="primary"
                        @click="query"
                    >
                        查询
                    </a-button>
                </div>
            </div>
            <div class="btn-group">
                <a-button @click="add">
                    新增
                </a-button>
                <a-button @click="del">
                    删除
                </a-button>
                <a-button @click="reset">
                    重置
                </a-button>
            </div>
            <a-table
                ref="TableInfo"
                row-key="bannerId"
                :row-selection="{
                    selectedRowKeys: selectedRowKeys,
                    onChange: onSelectChange,
                }"
                :scroll="{ x: 900 }"
                :columns="columns"
                :data-source="dataSource"
                :pagination="pagination"
                @change="handleTableChange"
            >
                <template
                    slot="status"
                    slot-scope="rows, record"
                >
                    <a-switch
                        :checked="Boolean(record.status)"
                        @change="onChange($event, record)"
                    />
                </template>
                <template
                    slot="operation"
                    slot-scope="rows, record"
                >
                    <a-icon
                        type="setting"
                        title="设置"
                        theme="twoTone"
                        style="color: #1890ff"
                        @click="edit(record)"
                    />&nbsp;
                    <a-icon
                        type="delete"
                        title="删除"
                        theme="twoTone"
                        two-tone-color="#ff3029"
                        @click="del(record)"
                    />
                </template>
            </a-table>

            <!-- 新增-编辑 -->
            <a-modal
                v-model="visible"
                :title="title"
            >
                <a-form-model
                    ref="ruleForm"
                    layout="horizontal"
                    :model="ruleForm"
                    :label-col="{ span: 4 }"
                    :wrapper-col="{ span: 20 }"
                    :rules="rules"
                >
                    <a-form-model-item
                        label="排序"
                        prop="sort"
                    >
                        <a-input-number
                            v-model="ruleForm.sort"
                            style="width: 100%"
                        />
                    </a-form-model-item>
                    <a-form-model-item
                        label="事项"
                        prop="matterId"
                    >
                        <a-select
                            v-model="ruleForm.matterId"
                            placeholder="请选择事项"
                        >
                            <a-select-option
                                v-for="item in matterList"
                                :key="item.matter"
                                :value="item.matterId"
                            >
                                {{ item.matter }}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item
                        label="封面图"
                        prop="url"
                    >
                        <div
                            style="display: flex;
							flex-direction: column;
							align-items: center;"
                        >
                            <a-upload
                                list-type="picture"
                                :show-upload-list="false"
                                :custom-request="
                                    (e) => {
                                        imgUpload(e, 'url');
                                    }
                                "
                                :remove="removeFiles"
                            >
                                <div style="text-align: center; border: 1px solid #333">
                                    <div
                                        v-if="!ruleForm.url"
                                        style="width: 340px; height: 137px;"
                                    />
                                    <img
                                        v-else
                                        width="300px"
                                        height="137px"
                                        :src="ruleForm.url"
                                    >
                                    <a-icon
                                        v-if="!ruleForm.url"
                                        style="position: absolute; top: 64px; left: 166px;"
                                        type="plus"
                                    />
                                </div>
                            </a-upload>
                        </div>
                    </a-form-model-item>
                </a-form-model>
                <template slot="footer">
                    <a-button
                        type="primary"
                        @click="handleOk(0)"
                    >
                        草稿
                    </a-button>
                    <a-button
                        type="primary"
                        @click="handleOk(1)"
                    >
                        发布
                    </a-button>
                    <a-button @click="handleCancel">
                        取消
                    </a-button>
                </template>
            </a-modal>
        </div>
    </PageLayout>
</template>
<script>
import PageLayout from '@/views/common/PageLayout';

export default {
    components: {PageLayout},
    data() {
        const validatePhone = (rule, value, callback) => {
            const reg = /^1[3-9][0-9]{9}$/;
            if (!reg.test(value)) {
                callback(new Error('请输入正确手机号'));
            } else {
                callback();
            }
        };
        return {
            matterList: [],
            visible: false,
            title: '新增',
            queryParams: {
                name: ''
            },
            pageParams: {
                current: 1,
                pageSize: 10,
                total: 0,
                'show-size-changer': true
            },
            addForm: {},
            ruleForm: {
                'bannerId': 0,
                'matter': '',
                'sort': 0,
                'status': 0,
                'url': ''
            },
            rules: {
                matter: [{ required: true, message: '请选择事项', trigger: 'blur' }],
                sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
            },
            dataSource: [],
            filteredInfo: null,
            sortedInfo: null,
            paginationInfo: null,
            pagination: {
                pageSizeOptions: ['10', '20', '30', '40', '100'],
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                showSizeChanger: true,
                showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
            },
            selectedRowKeys: [], // Check here to configure the default column
            loading: false
        };
    },
    computed: {
        columns() {
            let { sortedInfo, filteredInfo } = this;
            sortedInfo = sortedInfo || {};
            filteredInfo = filteredInfo || {};
            return [{
                title: '排序',
                dataIndex: 'sort',
                width: 80

            },
            {
                title: '事项',
                dataIndex: 'matter',
                width: 150

            },
            {
                title: '是否可用',
                key: 'status',
                scopedSlots: { customRender: 'status' },
                dataIndex: 'status',
                width: 150

            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                sorter: true,
                sortOrder: sortedInfo.columnKey === 'createTime' && sortedInfo.order
            },
            {
                title: '更新时间',
                dataIndex: 'updateTime',
                sorter: true,
                sortOrder: sortedInfo.columnKey === 'updateTime' && sortedInfo.order
            },
            {
                title: '操作',
                key: 'operation',
                scopedSlots: { customRender: 'operation' },
                dataIndex: 'operation',
                width: 200

            }];
        }
    },
    watch: {
        visible(val) {
            if (!val) {
                this.$refs.ruleForm.resetFields();
            }
        }
    },
    created() {
        this.fetch();
        this.$api.notice.matterList().then(res => {
            this.matterList = res.data.data;
        });
    },
    methods: {
        onChange(value, record) {
            record.status = Number(!record.status);
            this.$api.banner.save(record).then(res => {
                if (res.data.code == 200) {
                    this.$message.success('修改成功');
                } else {
                    this.$message.success('修改失败');

                }
            });
        },
        imgUpload(e, keyName) {
            let progress = { percent: 1 };
            const formData = new FormData();
            formData.append('fileUploads', e.file);
            formData.append('name', e.file.name);
            this.$message.loading('文件上传中')
                .then(() => {
                    return this.$api.fileUpload(formData);
                })
                .then((res) => {
                    if (res.data.code === 200) {
                        e.onSuccess(res, e.file);
                        this.$set(this.ruleForm, keyName, res.data.data[0].url);
                        progress.percent = 100;
                        return this.$message.success('上传成功');
                    }
                });
        },
        // 删除文件
        removeFiles() {
            this.ruleForm.img = '';
        },
        async cancel(record) {
            record.status = Number(!record.status);
            let res = await this.$api.banner.save(record);
            if (res.data.code === '200') {
                this.$message.warning('发布已取消');
            }
        },
        async status(record) {
            if (record.status) return;
            record.status = Number(!record.status);
            let res = await this.$api.banner.save(record);
            if (res.data.code === '200') {
                this.$message.success('发布成功！');
            }
        },
        handleTableChange(pagination, filters, sorter) {
            // 将这三个参数赋值给Vue data，用于后续使用
            this.paginationInfo = pagination;
            this.filteredInfo = filters;
            this.sortedInfo = sorter;
            this.fetch({
                sortField: sorter.field,
                sortOrder: sorter.order,
                ...this.queryParams,
                ...filters
            });
        },
        query() {
            this.fetch(this.queryParams);
        },
        reset() {
            this.queryParams = this.$options.data().queryParams;
            this.fetch();
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys;
        },
        add() {
            this.visible = true;
            this.title = '新增';
        },
        edit(record) {
            this.visible = true;
            this.title = '编辑';
            this.ruleForm = record;
        },
        del(record) {
            let list = record.bannerId ? [record.bannerId] : this.selectedRowKeys;
            this.$confirm({
                title: '提示',
                content: '确定删除操作数据?',
                onOk: () => {
                    this.$api.banner.del({id: list}).then(res => {
                        if (res.data.code === 200) {
                            this.$message.success(res.data.message);
                            this.fetch();
                        } else {
                            this.$message.warn(res.data.message);
                        }
                    });
                }
            });
        },
        handleOk(status) {
            this.ruleForm.status = status;
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    this.$api.banner.save(this.ruleForm).then(res => {
                        if (res.data.code == 200) {
                            this.fetch();
                            this.visible = false;
                            this.handleCancel();
                            this.$message.success(res.data.message);
                        } else {
                            this.$message.warn(res.data.message);
                        }
                    }).finally(() => {
                        this.visible = false;
                    });
                }
            });
        },
        handleCancel() {
            this.ruleForm = this.$options.data().ruleForm;
            this.visible = false;
        },
        fetch(params = {}) {
            // 显示loading
            this.loading = true;
            if (this.paginationInfo) {
                // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
                this.$refs.TableInfo.pagination.current = this.paginationInfo.current;
                this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize;
                params.pageSize = this.paginationInfo.pageSize;
                params.pageNum = this.paginationInfo.current;
            } else {
                // 如果分页信息为空，则设置为默认值
                params.pageSize = this.pagination.defaultPageSize;
                params.pageNum = this.pagination.defaultCurrent;
            }
            this.$api.banner.list({
                ...params
            }).then((r) => {
                console.log('rrrr', r.data.data);
                let data = r.data;
                const pagination = { ...this.pagination };
                pagination.total = data.total;
                this.dataSource = data.data;
                this.pagination = pagination;
                // 数据加载完毕，关闭loading
                this.loading = false;
            });
        }
    }
};
</script>
<style lang="less" scoped>
tr {

	.icon-close {
		display: none;
	}
}

/deep/ tr:hover {

	.icon-close {
		display: inline-block;
	}
}

.search-h {
	display: flex;
	justify-content: space-between;
	margin: 10px 0 8px;

	/deep/ .ant-form-item {
		margin-bottom: 0px !important;
	}
}

.btn-group {
	margin-bottom: 12px;
}
</style>
